/*
 * @Description: 栈（Stack）
 * @Autor: wangxin
 * @Date: 2020-06-09 10:02:58
 * @LastEditors: Seven
 * @LastEditTime: 2020-06-10 08:56:59
 */
class Stack {
  constructor() {
    this.items = {} // 使用js的对象来存储栈元素{0:1,1:2}
    this.count = 0 // 栈的长度
  }

  /* 添加元素 */
  push(element) {
    this.items[this.count] = element
    this.count += 1
  }

  /* 删除元素 */
  pop() {
    if (this.isEmpty()) {
      return undefined
    }
    this.count--
    const result = this.items[this.count]
    delete this.items[this.count]
    return result
  }

  /* size */
  size() {
    return this.count
  }

  isEmpty() {
    return this.count === 0
  }

  /* 返回最后一个元素 */
  peek() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.count - 1]
  }

  clear() {
    this.items = {}
    this.count = 0
  }

  toString() {
    if (this.isEmpty()) {
      return ''
    }
    let str = `${this.items[0]}`
    for (let i = 1; i < this.count; i++) {
      str = `${str},${this.items[i]}`
    }
    return str
  }
}

// 测试代码
var stack = new Stack()
stack.push(1)
stack.push(2)
